package com.wang.common;

import com.alibaba.fastjson.JSON;
import com.wang.utils.ResultEntity;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@Api(tags = "公共接口")
@RequestMapping("/common")
public class CommonController {


    @PostMapping("/upload")
    public Object uploadFiles(@RequestParam("file") MultipartFile file, @ModelAttribute FileDto fileDto) throws Exception {
        String originalFilename = file.getOriginalFilename();
        log.info("originalFilename:" + originalFilename);

        log.info("fileDto:" + JSON.toJSONString(fileDto));
        InputStream fis = file.getInputStream();
        // 使用InputStreamReader包装输入流，并指定UTF-8编码
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        // 使用BufferedReader包装字符流，并创建一个字符串变量用于存储每行的内容
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        // 循环读取每行的内容，并打印到控制台
//        PrintWriter pw = new PrintWriter(System.out, true);
        while ((line = br.readLine()) != null) {
            log.info(line);
//            pw.println(line);
        }
        // 关闭流资源
        br.close();
        isr.close();
        fis.close();

        return ResultEntity.ok(originalFilename);
    }


    @PostMapping("/download")
    public Object downloadFiles(@RequestBody FileDto fileDto, HttpServletResponse response) throws Exception {
        log.info("fileDto:" + JSON.toJSONString(fileDto));

        // 读取本地文件
        FileInputStream fis = new FileInputStream("D://test/a.txt");
        // 获取输出流
        ServletOutputStream os = response.getOutputStream();
        // 设置响应头的content-type为文本类型
        response.setContentType("text/plain");
        // 设置响应头的content-disposition为附件下载方式，指定文件名为a.txt
        response.setHeader("content-disposition", "attachment;filename=a.txt");
        // 将文件内容写入到响应体中
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        // 关闭流资源
        os.close();
        fis.close();

        return null;
    }

}
